//
//  BKUserCustomerServerceController.m
//  bestkeep
//
//  Created by windCould on 16/12/14.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKUserCustomerServerceController.h"
#import "BKMyCommon.h"
#import "SBJson.h"
#import "ChatViewController.h"
#import "Sign.h"
#import "BKUserStatusInfo.h"
#import "EaseMob.h"
#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"
//我的会员卡
@interface BKUserCustomerServerceController ()<UIWebViewDelegate,NJKWebViewProgressDelegate>
{
    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
}

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic,copy)NSString * userId;
@property (nonatomic,strong)ExceptionView * exceptionView;

@end

@implementation BKUserCustomerServerceController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.webViewTitle;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    [self loadWebView];
}


#pragma mark - loadWebView
-(void)loadWebView
{
    if(self.exceptionView) {
        
        [self.exceptionView dismiss];
        self.exceptionView = nil;
    }
    if (![BKMyCommon checkNetwork]) {
        
        __weak typeof(self) weakSelf = self;
        if(!self.exceptionView && self.isFirst) {
            
            ExceptionCodeType errorType = ExceptionCodeTypeRequestFailed;
            errorType = ExceptionCodeTypeNoNetwork;
            
            weakSelf.exceptionView = [ExceptionView exceptionViewWithType:errorType];
            ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:errorType handler:^(ExceptionViewAction *action) {
                
                [weakSelf loadWebView];
            }];
            
            [self.exceptionView addAction:retryAction];
            [self.exceptionView showInView:self.view];
            
            return;
        }
        
        
    }

    
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    
    
    UIButton *leftItemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftItemBtn.frame = CGRectMake(0, 0, 32, 18);
    [leftItemBtn setImage:[UIImage imageNamed:@"naviBack"] forState:UIControlStateNormal];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:@selector(goBack)];
    space.width = -16;
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftItemBtn];
    [leftItemBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItems = @[space, leftItem];
    
    
    NSURL *url =[NSURL URLWithString:_urlStr];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    
    self.webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.webView];
    self.webView.scrollView.scrollEnabled = YES;
    //    self.webView.delegate = self;
    _webView.delegate= _progressProxy;
    CGRect navBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0,
                                 navBounds.size.height - 2,
                                 navBounds.size.width,
                                 2);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [_progressView setProgress:0 animated:YES];
    [self.navigationController.navigationBar addSubview:_progressView];
    
    for (UIView *_aView in [self.webView subviews])
    {
        if ([_aView isKindOfClass:[UIScrollView class]])
        {
            [(UIScrollView *)_aView setShowsVerticalScrollIndicator:NO];
            //右侧的滚动条
        }
    }
    
    self.webView.scrollView.bounces = NO;
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view. mas_left).offset(0);
        make.top.equalTo(self.view.mas_top).mas_offset(0);
        make.right.equalTo(self.view. mas_right).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(0);
    }];
    
    [self.webView loadRequest:request];
    
}

- (void)didFinishLoadHtml{

    
    [_webView stringByEvaluatingJavaScriptFromString: @"OBJC.executeJs(\"init\",\"{}\")"];
    
}

-(void)didFailLoadHtml:(NSError *)error{
    
 
}

-(void)shouldStartLoadWithRequest:(NSString*)requestString{
    
    NSString *header = @"http://objc/";
    if ([requestString hasPrefix:header]) {
        
        NSArray *components = [requestString componentsSeparatedByString:@"http://objc/"];
        if (components.count > 1) {
            NSUInteger range = [requestString rangeOfString:@"{"].location;
            NSString *b = [requestString substringFromIndex:range];
            NSDictionary *param_dic = [b JSONValue];
            if ([[param_dic objectForKey:@"action"] isEqualToString:@"open"]) {
                NSString * number = [param_dic objectForKey:@"target"];
                if([number isEqualToString:@"pagechat"]){
                    NSDictionary *dic = [param_dic objectForKey:@"parameters"];
                    self.urlStr = @"";
                    NSLog(@"%@",dic);
                    if ([dic[@"msgType"] isEqualToString:@"2"]) {
                        NSString *string = [[NSString alloc]init];
                        EMError *error = nil;
                        
                        string = [NSString stringWithFormat:@"bestkeep%@",_userId];
                        NSString *time = [Sign getSystemTime];
                        NSDictionary *dic = @{@"useN": string};
                        NSString *strSign = [Sign sign:dic time:time];
                        
                        NSLog(@"====%@",string);
                        BOOL isSuccess = [[EaseMob sharedInstance].chatManager registerNewAccount:strSign password:@"bestkeep_pwd" error:&error];
                        NSLog(@"====%d",isSuccess);
                        if (isSuccess) {
                            NSLog(@"注册成功");
                        }
                        NSDictionary *loginInfo = [[EaseMob sharedInstance].chatManager loginWithUsername:strSign password:@"bestkeep_pwd" error:&error];
                        if (!error && loginInfo) {
                            NSLog(@"登录成功");
                            NSLog(@"%@", loginInfo);
                        }
                        ChatViewController *chat = [[ChatViewController alloc] initWithChatter:@"sky" isGroup:NO];
                        
                        chat.title = BKMyLocalizedString(@"BKUserMyQuestionCustomerServices");
                        
                        chat.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:chat animated:YES];
                    }else if ([dic[@"msgType"]isEqualToString:@"3"]){
                        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"400-999-1813" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                        alertV.tag = 230;
                        [alertV show];
                    }
                    
                }
                else{
                    
                    NSDictionary *dic = [param_dic objectForKey:@"parameters"];
                    BKUserCustomerServerceController *webView = [[BKUserCustomerServerceController alloc] init];
                    webView.urlStr = param_dic[@"target"];
                    webView.webViewTitle = dic[@"title"];
                    webView.isFirst = NO;
                    [self.navigationController pushViewController:webView animated:YES];
                }
            }
        }
    }
}


-(NSString *)userId
{
    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
    return [NSString stringWithFormat:@"%@",userInfo.userId];
}

#pragma mark - 电话拨号
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag==230){
        switch (buttonIndex) {
            case 1:
            {
                NSLog(@"拨打电话");
                NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", @"400-999-1813"]];
                [[UIApplication sharedApplication] openURL:url];
            }
                break;
                
            default:
                break;
        }
    }
    
}

#pragma mark - UIWebViewDelegate

-(void)webViewDidStartLoad:(UIWebView *)webView
{

   
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {//html加载完后触发
    

    [self didFinishLoadHtml];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.webView.scrollView.scrollEnabled = YES;
    
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [self didFailLoadHtml:error];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *requestString = [[request URL]absoluteString];//获取请求的绝对路径.
    requestString = [requestString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self shouldStartLoadWithRequest:requestString];
    
    return YES;
}


-(void)goBack{
    
    if([_webView canGoBack]){
        
        [_webView goBack];
        
    }else{
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _progressView.hidden=YES;

}
#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
    if (!self.title) {
        self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    }
}

@end
